import { Component, OnInit } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { CacheService } from './../../services/cache.service';
import { NetService } from './../../services/net.service';
@Component({
  selector: 'app-role-list',
  templateUrl: './role-list.component.html',
  styleUrls: ['./role-list.component.scss']
})
export class RoleListComponent implements OnInit {
  public userInfo: object = null;
  public headers = ['名称', '代码', 'ID', '操作'];
  public dataSet = [];
  public modalVisible = false;
  public roleForm: FormGroup;
  constructor(
    private cacheService: CacheService,
    private fb: FormBuilder,
    private net: NetService,
    private nzmsg: NzMessageService,
  ) {}

  addRole() {
    this.modalVisible = true;
  }
  async delRole(item) {
    const result = await this.net.delete(`/api/roles/${item._id}`);
    if (result) {
      this.nzmsg.success('删除角色成功!');
      this.getRoleList();
    }
  }
  modalOk(): void {
    Object.keys(this.roleForm.controls).forEach(item => {
      this.roleForm.controls[item].markAsDirty();
      this.roleForm.controls[item].updateValueAndValidity();
    });
    if (this.roleForm.valid) {
      this.modalVisible = false;
      this.submitForm();
    }
  }
  async submitForm() {
    const result = await this.net.post('/api/roles', this.roleForm.value);
    if (result) {
      this.nzmsg.success('创建角色成功！');
      this.getRoleList();
    }
  }
  modalCancel(): void {
    this.modalVisible = false;
    this.roleForm = this.fb.group({
      name: [null, [Validators.required]],
      code: [null, [Validators.required]]
    });
  }
  async getRoleList() {
    const result = await this.net.get('/api/roles');
    if (result) {
      this.dataSet = result['data'];
    }
  }
  async ngOnInit() {
    this.roleForm = this.fb.group({
      name: [null, [Validators.required]],
      code: [null, [Validators.required]]
    });
    this.userInfo = await this.cacheService.getUserInfo();
    this.getRoleList();
  }
}
